import cv2
import cv
import sys
import cpoo_tools as tools
import pylab
import numpy as np

img = cv.LoadImage(sys.argv[1])
#img = cv.LoadImage("meat/rgb.png")
# eig_image = cv.CreateMat(img.rows, img.cols, cv2.CV_32FC1)
# temp_image = cv.CreateMat(img.rows, img.cols, cv2.CV_32FC1)
# for (x,y) in cv.GoodFeaturesToTrack(img, eig_image, temp_image, 100, 0.04, 1.0, useHarris = True):
#  print "good feature at", x,y

#dst = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_16S, img.channels)
#laplace = cv.Laplace(img, dst)
#cv.ShowImage('sth', laplace)
#cv.WaitKey()

print "height: "+str(img.height)
print "width: "+str(img.width)
print type(img)

red = cv.CreateImage(cv.GetSize(img), img.depth, 1)
blue = cv.CreateImage(cv.GetSize(img), img.depth, 1)
green = cv.CreateImage(cv.GetSize(img), img.depth, 1)



print type(red)
print "reddepth: "+str(red.depth)
#print img.rows
#print img.cols
#print img[100,100][1]

#red = img

for y in range(0,img.height):
  for x in range(0,img.width):
      #rED = pImg[i*img->widthStep + j*img->nChannels + 2];
      #print str(x)+", "+str(y)+"value: "+str(img[y,x][2])
#      blue[y,x] = img[y,x][0];
#      green[y,x] = img[y,x][1];
      red[y,x] = img[y,x][2];


scores = list()
THRESH = 10
OPTIMAL_HEIGHT = img.height / 20

redunblurred = red
red = cv2.GaussianBlur(tools.cv2array(red),(5,5),OPTIMAL_HEIGHT/2)
red = tools.array2cv(red)

print "optimal height: "+str(OPTIMAL_HEIGHT)
weight_centers = dict();
#for y in range(0,img.height):
  #score=0
  #values=set()
  #last_pos = dict();
  #first_pos = dict();
  #local_scores = dict();
  #map(value, last_position)
  #map(value, score)
  #if last occurence long ago - zero the score
  #score= max score for row!
  #for x in range(0, img.width):
  #  color = red[y,x]	
  #  if color in values:
  #    if y!=0 and x!= 0 and abs(red[y,x-1] - red[y,x])>THRESH:
  #      if x-first_pos[color]>img.width:
  #        #print "rejection criterion triggered"
  #        local_scores[color]=0
  #      else:
  #        local_scores[color]=local_scores[color]+1#red.width/(x-last_pos[color])
  #      if y in weight_centers.keys():
  #        print "this is sth for dictionary"
  #        weight_centers[y][0]+=x
  #        weight_centers[y][1]+=1
  #      else:
  #        weight_centers[y]=[x,1]
  #  else:
      #first encounter of given color within a line
  #    values.add(red[y,x])
  #    local_scores[color] = 0
  #    first_pos[color]=x
  #  last_pos[red[y,x]]=x
  #score = sum(local_scores.values())
  #print "row: "+str(y)+" score: "+str(score)+" values.size="+str(len(values))
  #scores.append(score)
  
# hmm, remove the frame results
for i in range(OPTIMAL_HEIGHT, -1, -1):
  scores[i]=scores[i+1]
  scores[len(scores)-1-i]=scores[len(scores)-2-i]

print scores

diffs = list()
global_min=0
global_max=0
min_sum = 0
max_sum = 0
diffs.append(0)
for i in range(1,len(scores)):
  diffs.append(scores[i]-scores[i-1])
#  if i>1:
#    positive_sum = max(diffs[i],0)+max(diffs[i-1],0)+max(diffs[i-2],0)
#    negative_sum = min(diffs[i],0)+min(diffs[i-1],0)+min(diffs[i-2],0)
#    if positive_sum > max_sum:
#      max_sum = positive_sum
#      global_max=i
#    elif negative_sum < min_sum:
#      min_sum = negative_sum
#      global_min=i
#  print str(i)+" row: "+str(diffs[i])

#for i in range(0, len(scores)-1):
#  if diffs[i] * diffs[i+1] >0:
#    diffs[i]=diffs[i]+diffs[i+1]

#for i in range(0,len(diffs)):
#  if diffs[i]>diffs[global_max]:
#    global_max=i
#  elif diffs[i]<diffs[global_min]:
#    global_min=i

print "weight_centers"
avg_center=0
counter=0;
for key in weight_centers.keys():
  if key> global_max and key<global_min:
    counter +=1
    avg_center+=weight_centers[key][0]/weight_centers[key][1]
    
avg_center/=counter
print "Mass center (X) for datestamp: "+str(avg_center)
    
print "min: "+str(global_min)+"("+str(min_sum)+"), max: "+str(global_max)+" ("+str(diffs[global_min])+")"

clipped = cv.GetSubRect(redunblurred, (avg_center, global_max, img.width-avg_center, global_min-global_max))
cv.ShowImage("clipping zone", clipped) 
#cv.WaitKey()
#cv.ShowImage("green",green) 
#cv.WaitKey()
#cv.ShowImage("blue",blue) 
#cv.WaitKey()
#cv.ShowImage("orignal",img) 
#thresh = cv2.adaptiveThreshold(np.asarray(clipped),255,1,1,11,2)
#cv.SaveImage("clipped.png", clipped)
#cv.SaveImage("thresh.png", cv.fromarray(thresh))
#cv.ShowImage("clipped", cv.fromarray(clipped))
cv.WaitKey()
